//
//  QLMVeriCodeVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2018/2/5.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "QLMVeriCodeVC.h"
#import "JPUSHService.h"

#import "MQVerCodeInputView.h"
#import "UIView+MQ.h"

@interface QLMVeriCodeVC (){
    NSString *veriCodeStr;
}

@end

@implementation QLMVeriCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor=[UIColor whiteColor];
    
    NSString *testStr=[NSString stringWithFormat:@"验证码已发送至手机：%@",_phoneNumber];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:testStr];
    [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf5c407) range:NSMakeRange(10,[str length]-10)];
    _tipsLabel.attributedText=str;
    
    _codeTextField.hidden=YES;
    
    MQVerCodeInputView *verView = [[MQVerCodeInputView alloc]initWithFrame:CGRectMake(10, _tipsLabel.frame.size.height+_tipsLabel.frame.origin.y+20, kScreen_width-10*2, 50)];
    verView.maxLenght = 6;//最大长度
    verView.keyBoardType = UIKeyboardTypeNumberPad;
    [verView mq_verCodeViewWithMaxLenght];
    verView.block = ^(NSString *text){
        veriCodeStr=text;
    };
    [self.view addSubview:verView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self sendCodeStr];
}

- (IBAction)senderTimerAction:(UIButton *)sender {
    [self sendCodeStr];
}

- (void)sendCodeStr{
    
    __block NSInteger time = 119; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.timerBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.timerBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                self.timerBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.timerBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [self.timerBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                self.timerBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:_phoneNumber forKey:@"phoneNumber"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/smsCode" withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(responseObject[@"msg"]);
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)commitBtnAction:(UIButton *)sender {
    [self requestNetData];
}

- (void)requestNetData{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:_phoneNumber forKey:@"phoneNumber"];
    
    if (veriCodeStr.length==6) {
        [dic setObject:veriCodeStr forKey:@"code"];
    }else{
        ETToast(@"请输入正确的验证码");
    }

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/smsLogin" withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            NSString *userid= [[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"userId"];
                            NSString *userName=[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"userName"];
                            
                            [[NSUserDefaults standardUserDefaults] setObject:userid forKey:kLoginUserId];
                            [[NSUserDefaults standardUserDefaults] setObject:userName forKey:kLoginUserName];
 
                            [self saveUserInfo:responseObject[@"token"]];
                            
                            NSString *auserId = [NSString stringWithFormat:@"%@",userid];
                            [JPUSHService setAlias:auserId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                            } seq:0];
                            
                            [self.navigationController dismissViewControllerAnimated:YES completion:nil];

                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)saveUserInfo:(NSString *)token{
    [[NSUserDefaults standardUserDefaults] setObject:_phoneNumber forKey:kLoginPhoneName];
    [[NSUserDefaults standardUserDefaults] setObject:_passportStr forKey:kLoginPassport];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:kLoginToken];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
